<?php
namespace Aliyun\Controller;
use Aliyun\Controller\AliyunController;
require_once (__DIR__.'/Aliyun/aliyun.php');
define('OSS', 'http://bbt-yyy.oss-cn-beijing-internal.aliyuncs.com/');
class AliyunController{
    protected function config(){
	     $config = array(
	    'AccessKeyId' => 'YHWXk7TLtxnE3aHW',    //AccessKeyId
	    'AccessKeySecret' => 'lm0VhxQx1p8KuETgCjSL1gbcLV8zCY',//AccessKeySecret
	    'domain' => OSS,
	    'Bucket' => 'bbt-yyy',
	    'Endpoint' => 'http://oss-cn-beijing-internal.aliyuncs.com',
	    );
		return $config;
	}
    /**
     * 本地上传错误信息
     * @var string
     */
    private $error      =   '';

    /**
     * 构造函数，用于设置上传根路径
     * @param array  $config 配置
     */
    public function __construct($config){
        /* 默认配置 */
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 检测上传根目录(OSS上传时支持自动创建目录，直接返回)
     * @param string $rootpath   根目录
     * @return boolean true-检测通过，false-检测失败
     */
    public function checkRootPath($rootpath){
        /* 设置根目录 */
        $this->rootPath = trim($rootpath, './') . '/';
        return true;
    }

    /**
     * 检测上传目录(OSS上传时支持自动创建目录，直接返回)
     * @param  string $savepath 上传目录
     * @return boolean          检测结果，true-通过，false-失败
     */
    public function checkSavePath($savepath){
        return true;
    }

    /**
     * 创建文件夹 (OSS上传时支持自动创建目录，直接返回)
     * @param  string $savepath 目录名称
     * @return boolean          true-创建成功，false-创建失败
     */
    public function mkdir($savepath){
        return true;
    }
		/*
	* $img_path 被压缩的图片的路径
	* $save_path 压缩后图片的存储路径
	* $scale 图片比列，默认等比例缩放
	* $thumb_w 压缩的宽800px
	* $is_del 是否删除原文件，默认删除
	*/

	public function thumb_img($path,$scale=0,$thumb_w=800,$is_del=false){
		$image = new \Think\Image();
		$image->open($path);
		//显示图片比列
		if($scale){
			$width = $image->width();
			$height = $image->height();
			$whscale = sprintf("%.2f",$width/$height);
			if($scale>=$scale-0.1 || $whscale<=$scale+0.1){
				$this->error("图片宽高比为".$whscale."不符合上传要求，请修改图片");
			}
		}
		$width = $image->width(); // 返回图片的宽度
		if($width > $thumb_w){
			$width = $width/$thumb_w; //取得图片的长宽比
			$height = $image->height();
			$thumb_h = ceil($height/$width);
		}
		$file_path = (microtime(true)*10000).'.'.$image->type($path);
		$real_file_path = RUNTIME_PATH.$file_path;
		$image->thumb($thumb_w, $thumb_h)->save($real_file_path);
		if($is_del) @unlink($path); //删除源文件
		return $file_path;
	}
    /**
     * 保存指定文件
     * @param  array   $file    保存的文件信息
     * @param  boolean $replace 同名文件是否覆盖
     * @return boolean          保存状态，true-成功，false-失败
     */
    public function save(&$file,$save_path,$scale=0,$thumb_w=800,$replace=true) {
		//如果文件路径不存在则创建
		$save_path = $save_path.'/'.date("Y").'/'.date("m").'/';
		$file['path'] =$save_path;
    	$file['name'] = $this->thumb_img($file['tmp_name'],$scale,$thumb_w);
        $client = $this->client();
		$config = $this->config();
		$ContentType = \Guzzle\Http\Message\PostFile::setContentType($file['type']);

/*		print_r(array(
			'ContentType'=>$file['type'],
			'Bucket'    => $config['Bucket'],
			'Key'       => $file['path'] . $file['name'],
			'Content'   => fopen(RUNTIME_PATH.$file['name'],'r'),
			'ContentLength'=> $file['size']*2,
		));exit;*/
		$save = $client->putObject(array(
			'ContentType'=>$file['type'],
            'Bucket'    => $config['Bucket'],
            'Key'       => $file['path'] . $file['name'],
            'Content'   => fopen(RUNTIME_PATH.$file['name'],'r'),
            'ContentLength'=> filesize(RUNTIME_PATH.$file['name']),
            ));
        if ($save) {
//		 	@unlink(RUNTIME_PATH.$file['name']);// 不用删除/清理缓存时候会自动删除
            return $file;
        }else{
            return false;
        }
    }

    public function save_file(&$files,$save_path) {
		//如果文件路径不存在则创建
		$content =fopen($files, "r");
		$file = fstat($content);
		$save_path = $save_path.'/'.date("Y").'/'.date("m").'/';
		$file['path'] =$save_path;
    	$file['name'] = (microtime(true)*10000).strrchr($files,'.');
        $client = $this->client();
		$config = $this->config();
		$ContentType = \Guzzle\Http\Message\PostFile::setContentType($file['type']);
		$save = $client->putObject(array(
			'ContentType'=>$file['type'],
            'Bucket'    => $config['Bucket'],
            'Key'       => $file['path'] . $file['name'],
            'Content'   => $content,
            'ContentLength'=> $file['size'],
            ));
        if ($save) {
            return $file;
        }else{
            return false;
        }
    }
	/**
	 * 删除图像
	 */
	 public function delete($file){
        $client = $this->client();
		$config = $this->config();
	 	$delete = $client->deleteObject(array(
            'Key'       => $file,
            'Bucket'    => $config['Bucket'],
            ));
	 }
    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError(){
        return $this->client->errorStr;
    }

    //创建client对象
    function client(){
		$config = $this->config();
        $client = \Aliyun\OSS\OSSClient::factory(array(
            'Endpoint' => $config['Endpoint'],
            'AccessKeyId' => $config['AccessKeyId'],
            'AccessKeySecret' => $config['AccessKeySecret'],
        ));
        return $client;
    }
}